<?php

namespace Frieza\Modules\Version\Controllers;

use App\Exceptions\InputErrorException;
use App\Http\Controllers\Controller;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use Frieza\Modules\Topic\Extensions\Widgets\Form;
use Doraemon\tools\Version;
use Illuminate\Support\MessageBag;

class VersionController extends Controller
{
    public function index(Request $request, Content $content)
    {
        $title = '版本管理';
        $data = Version::getVersionData();
        $form = new Form($data);
        $form->text('version', '最新版本(建议升级到的版本非强制)')->required(true)->placeholder('例：5.14.0');
        $form->text('min_version', '最低支持版本（小于这个版本弹出强制升级）')->required(true)->placeholder('例：5.13.0');
        $form->text('android_code', 'Android最新version code构建版本号')->required(true);
        $form->text('min_android_code', 'Android最低支持version code构建版本号')->required(true);
        $form->text('download_url', 'Android apk下载安装地址')->required(true);
        $form->text('hash_code', 'hash code（Android）')->required(true);
        $form->text('title', '更新弹窗的标题')->required(true);
        $form->textarea('changelog', '更新日志')->required(true);
        $form->action('/admin/version/index/save');
        return $content
            ->header($title)
            ->breadcrumb(
                [
                    'text' => $title,
                    'url' => '/version/index'
                ]
            )
            ->body($form);
    }

    public function save(Request $request)
    {
        $request = $request->all();
        unset($request['_token']);
        if(!preg_match('/^[1-9][0-9]*(\.[0-9]{1,2}){2}$/',$request['version'])){
            throw new InputErrorException('格式错误，例（5.14.0）', InputErrorException::DEFAULT_CODE, 'version');
        }
        if(!preg_match('/^[1-9][0-9]*(\.[0-9]{1,2}){2}$/',$request['min_version'])){
            throw new InputErrorException('格式错误，例（5.13.0）', InputErrorException::DEFAULT_CODE, 'min_version');
        }

        if(version_compare($request['version'],$request['min_version'],'<')){
            throw new InputErrorException('最低支持版本不应大于最新版本', InputErrorException::DEFAULT_CODE, 'min_version');
        }

        $data = json_encode($request);
        $result = Version::setVersionData($data);
        if ($result) {
            $success = new MessageBag([
                'title' => '保存成功'
            ]);
            return back()->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '保存失败'
            ]);
            return back()->with(compact('error'));
        }
    }
}
